package my;

import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.soap.*;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

@WebService(serviceName = "StudentService", portName = "StudentPort",
        targetNamespace = "http://my/",
        endpointInterface = "my.IService")
public class ServiceImpl implements IService {

    @Resource
    private WebServiceContext wsContext;

    @Override
    public String hello(String username) throws SOAPException {
        System.out.println("Hello方法被调用，参数: " + username);

        try {
            // 获取MessageContext
            MessageContext mc = wsContext.getMessageContext();

            System.out.println("ServiceImpl: MessageContext类型: " + mc.getClass().getName());

            // 关键修改：从Handler设置的属性中获取Header信息
            // 这是JAX-WS中从Handler获取数据的正确方式
            String headerInfo = (String) mc.get("STUDENT_HEADER_INFO");
            String sno = (String) mc.get("STUDENT_SNO");
            String sname = (String) mc.get("STUDENT_SNAME");
            String time = (String) mc.get("STUDENT_TIME");

            if (headerInfo != null) {
                System.out.println("=== ServiceImpl从Handler获取的Header信息 ===");
                System.out.println("完整信息: " + headerInfo);
                if (sno != null) System.out.println("学号: " + sno);
                if (sname != null) System.out.println("姓名: " + sname);
                if (time != null) System.out.println("时间: " + time);
                System.out.println("==========================================");

                // 现在你可以在业务逻辑中使用这些Header信息了
                // 例如：验证学号、记录访问时间、个性化响应等

            } else {
                System.out.println("ServiceImpl: 未从Handler获取到Header信息");
                System.out.println("这可能是因为：");
                System.out.println("1. 客户端没有发送student header");
                System.out.println("2. Handler没有正确解析header");
                System.out.println("3. MessageContext属性传递失败");

                // 打印所有可用的属性键，用于调试
                System.out.println("MessageContext中的所有属性:");
                for (Object key : mc.keySet()) {
                    Object value = mc.get(key);
                    System.out.println("  " + key + " = " + (value != null ? value.getClass().getSimpleName() : "null"));
                }
            }

            // 根据是否有Header信息返回不同的响应
            if (sname != null) {
                return "Hello, " + sname + " (学号: " + sno + ")";
            } else {
                return "Hello, " + username;
            }

        } catch (Exception e) {
            System.err.println("ServiceImpl: 处理Header时发生异常: " + e.getMessage());
            e.printStackTrace();
            return "Hello, " + username + " (处理异常)";
        }
    }
}